<template>
  <div class="wrapper">
    <h1>体检预约-登录</h1>
    <section>
      <div class="input-box">
        <div>
          <img class="icon" :src="'src/img/userId.png'" alt="账号图标">
        </div>
        <i class="fa fa-user-o"></i>
        <input type="text" placeholder="输入手机号" v-model="state.users.userId">
      </div>


      <!-- Password or Verification Code Input Box -->
      <div class="input-box" v-if="!showVerification">
        <div>
          <img class="icon" :src="'src/img/password.png'" alt="密码图标">
        </div>
        <i class="fa fa-lock"></i>
        <input type="password" placeholder="输入登录密码" v-model="state.users.password">
      </div>

      <div class="input-box" v-else>
        <div>
          <img class="icon-code" :src="'src/img/code.png'" alt="验证码图标">
        </div>
        <i class="fa fa-lock"></i>

        <input type="text" placeholder="输入验证码" v-model="state.verification.verificationCode">
        <div class="send-code-wrapper">
          <div class="but active" @click="sendVerificationCode">
            {{ sendCodeButtonText }}
          </div>
        </div>
      </div>



      <!-- Register, Forget Password, Toggle Verification Buttons -->
      <div class="reg-box">
        <p @click="toRegister">注册</p>
        <p>忘记密码？</p>
        <p class="verify-login" @click="toggleVerification">{{ verificationButtonText }}</p>
      </div>

      <!-- Login Button -->
      <div class="button-box" @click="login" :class="{ 'disabled': !agreedToTerms }">
        {{ loginButtonText }}
      </div>

      <br>
      <!-- Agreement Checkbox -->
      <div class="agreement-checkbox">
        <input type="checkbox" id="agreement" v-model="agreedToTerms">
        <label for="agreement">我已阅读并同意<a href="#">《用户协议》</a>和<a href="#">《隐私政策》</a></label>
      </div>
    </section>
  </div>
</template>

<script>
import { reactive, ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { setSessionStorage } from "../common.js";

export default {
  setup() {
    const router = useRouter();

    const state = reactive({
      users: {
        userId: "",
        password: ""
      },
      verification: {
        verificationCode: ""
      }
    });

    const showVerification = ref(false);
    const agreedToTerms = ref(false);

    const canSendCode = ref(true);
    const countdownSeconds = ref(60);
    const sendCodeButtonText = ref("发送验证码");

    async function login() {
      if (!agreedToTerms.value) {
        alert("请先阅读并同意《用户协议》和《隐私政策》！");
        return;
      }

      if (!showVerification.value) {
        if (state.users.userId === "" || state.users.password === "") {
          alert("手机号码和密码不能为空！");
          return;
        }
      } else {
        if (state.users.userId === "" || state.verification.verificationCode === "") {
          alert("手机号码和验证码不能为空！");
          return;
        }
      }

      try {
        let response;
        if (!showVerification.value) {
          response = await axios.post("http://localhost:8080/users/login", {
            userId: state.users.userId,
            password: state.users.password
          });
        } else {
          response = await axios.post("http://localhost:8080/code/login", {
            userId: state.users.userId,
            VICode: state.verification.verificationCode
          });
        }

        const { code, msg, user } = response.data;

        if (code === 200) {
          setSessionStorage("user", user);
          setSessionStorage("verificationCode", state.verification.verificationCode);
          router.push("/index");
        } else if (code === 600) {
          alert("账号不存在，请确认手机号是否正确。");
        } else if (code === 800) {
          alert("密码错误，请重新输入。");
        } else {
          alert(`登录失败: ${msg}`);
        }
      } catch (error) {
        if (error.response && error.response.status === 400) {
          alert("登录失败: 请求错误，请检查输入。");
        } else {
          console.error("登录请求错误:", error);
          alert("网络错误，请稍后重试。");
        }
      }
    }

    function toRegister() {
      router.push("/register");
    }

    function toggleVerification() {
      showVerification.value = !showVerification.value;
      if (showVerification.value) {
        countdownSeconds.value = 60;
        startCountdown();
      } else {
        clearInterval(interval);
        sendCodeButtonText.value = "发送验证码";
        canSendCode.value = true;
      }
    }

    let interval;

    function startCountdown() {
      interval = setInterval(() => {
        countdownSeconds.value--;
        if (countdownSeconds.value === 0) {
          clearInterval(interval);
          sendCodeButtonText.value = "重新发送";
          canSendCode.value = true;
        }
      }, 1000);
    }

    async function sendVerificationCode() {
      if (state.users.userId === "") {
        alert("请输入手机号码！");
        return;
      }

      try {
        await axios.post("http://localhost:8080/code/sendCode", {
          phone: state.users.userId
        });
        canSendCode.value = false;
        startCountdown();
      } catch (error) {
        console.error("发送验证码失败:", error);
        alert("发送验证码失败，请稍后重试。");
      }
    }

    return {
      state,
      showVerification,
      agreedToTerms,
      login,
      toRegister,
      toggleVerification,
      sendVerificationCode,
      verificationButtonText: computed(() => {
        return showVerification.value ? "使用密码登录" : "验证码登录";
      }),
      sendCodeButtonText: computed(() => {
        return canSendCode.value ? "验证码" : `重新发送(${countdownSeconds.value}s)`;
      }),
      loginButtonText: computed(() => {
        return showVerification.value ? "验证码登录" : "登录";
      })
    };
  }
};
</script>


<style scoped>
/*********************** 总容器 ***********************/
.wrapper {
  width: 100%;
  min-height: 80vh;
  /* 设置最小高度为视口高度 */
  height: 100vh;
  /* 设置高度为视口高度的 140% */
  background: linear-gradient(135deg, #ffcc66, #ff9966, #ff6699);
  /* 使用渐变色，包括黄色、橙色和粉红色 */
  overflow: hidden;
}

/*********************** 标题部分 ***********************/
h1 {
  text-align: center;
  color: #FFF;
  font-size: 9.5vw;
  font-weight: 500;
  margin-top: 13vh;
  margin-bottom: 3vh;
}

/*********************** 内容部分 ***********************/
.icon {
  float: left;

  width: 70%;
  height: 5.2vw;
}

.icon-code {
  float: left;

  width: 150%;
  height: 5.2vw;
}

.but {
  /* float: right; */
  display: inline-block;

  width: 20%;
  height: 5.2vw;
}

/* 输入框的样式 */
section {
  width: 86vw;
  margin: 0 auto;
  background-color: #9cdae3;
  border-radius: 2.4vw;

  box-sizing: border-box;
  padding: 6vw;
}

section .input-box {
  width: 100%;
  height: 50px;
  /* 根据需要调整高度 */
  border: 1px solid transparent;
  /* 初始边框为透明，后面会添加渐变色 */
  border-radius: 8px;
  /* 调整为更小的圆角 */
  margin-top: 20px;
  /* 调整上边距 */

  display: flex;
  align-items: center;
  padding: 0 15px;
  /* 调整内边距 */
  box-sizing: border-box;
  /* 确保内边距不会增加元素宽度 */

  background-color: #fff;
  /* 背景色为白色或者需要的基础色 */

  /* 添加渐变色边框 */
  border-image: linear-gradient(to right, #ffcc66, #ff9966, #2c2c5a);
  /* 渐变色边框 */
  border-image-slice: 1;
  /* 保持渐变色覆盖整个边框 */
}


section .input-box i {
  margin: 0 3.6vw;
  font-size: 5.4vw;
  color: #CCC;
}

section .input-box input {
  border: none;
  outline: none;
}

section .reg-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 5vw;
  margin-bottom: 2vw;
}

section .reg-box p {
  font-size: 3.3vw;
  color: #2D727E;
  user-select: none;
  cursor: pointer;
}

section .button-box {
  width: 100%;
  height: 13vw;
  border-radius: 2vw;
  background-color: #70B0BC;

  text-align: center;
  line-height: 13vw;
  font-size: 4.6vw;
  color: #FFF;
  letter-spacing: 1vw;

  user-select: none;
  cursor: pointer;
}
section .send-code-wrapper {
  width: 20%; /* 占据父容器的 20% 宽度 */
  display: flex;
  justify-content: center; /* 居中对齐 */
}

section .send-code-wrapper .but {
  width: 120%; /* 按钮宽度占据父容器的全部 */
  height: 80%; /* 按钮高度占据父容器的全部 */
  background-color: #4CAF50; /* 绿色背景 */
  color: #FFF; /* 白色文字 */
  text-align: center; /* 文字居中 */
  line-height: 25px; /* 文字行高与按钮高度一致 */
  border-radius: 7px; /* 圆角边框 */
  cursor: pointer; /* 鼠标指针样式 */
}

section .send-code-wrapper .but:hover {
  background-color: #45a049; /* 鼠标悬停时的背景色 */
}
/*********************** footer部分 ***********************/
footer {
  width: 100%;
  margin: 0 auto;
  margin-top: 50vw;
  font-size: 3.8vw;
  align-items: center;
  color: #FFF;
  background: linear-gradient(135deg, #ffcc66, #ff9966, #ff6699);
  /* 使用渐变色，包括黄色、橙色和粉红色 */

}

footer div {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

footer div .line {
  align-items: center;
  width: 22vw;
  height: 1px;
  background-color: #FFF;
}

footer>p {
  align-items: center;
  text-align: center;
  margin-top: 2vw;
}
</style>